// 39.组合总和
package LeetcodeHot100;

import java.util.ArrayList;
import java.util.List;

public class Solution039 {
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        BackTrace(candidates, target, 0, new ArrayList<>(), 0);
        return result;
    }

    private void BackTrace(int[] candidates, int target, int cur, ArrayList<Integer> list, int sum) {
        if (sum == target && cur <= candidates.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        if (sum > target || cur >= candidates.length)
            return;
        int count = 0;
        BackTrace(candidates, target, cur + 1, list, sum);
        while (sum < target) {
            sum += candidates[cur];
            list.add(candidates[cur]);
            count++;
            BackTrace(candidates, target, cur + 1, list, sum);
        }
        while (count-- != 0) {
            list.remove(list.size() - 1);
        }
    }
}
